package com.goldenautumn.prefabricate

import android.os.Build
import android.os.Bundle
import android.util.SparseArray
import android.view.KeyEvent
import android.view.View
import androidx.annotation.IdRes
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.SPUtils
import com.goldenautumn.prefabricate.activity.cart.CartFragment
import com.goldenautumn.prefabricate.activity.category.CategoryFragment
import com.goldenautumn.prefabricate.activity.home.HomeFragment
import com.goldenautumn.prefabricate.activity.mine.MineFragment
import com.goldenautumn.prefabricate.databinding.ActivityMainBinding
import com.goldenautumn.prefabricate.utils.clickIsLogin
import com.goldenautumn.prefabricate.utils.onCenterToast
import kotlinx.coroutines.isActive
import qncx.external.common.Global
import qncx.external.common.base.BaseActivity

class MainActivity : BaseActivity<ActivityMainBinding>() {

    var isBack = false

    private var lastId = -1

    private val fragments: SparseArray<Fragment> = SparseArray()

    override fun getLayoutId(): Int  = R.layout.activity_main

    override fun onCreate(savedInstanceState: Bundle?) {
        if (Build.VERSION.SDK_INT >= 34) {
            overrideActivityTransition(OVERRIDE_TRANSITION_OPEN,qncx.external.common.R.anim.anim_alpha_show, qncx.external.common.R.anim.anim_alpha_hide)
        } else overridePendingTransition(qncx.external.common.R.anim.anim_alpha_show, qncx.external.common.R.anim.anim_alpha_hide)
        super.onCreate(savedInstanceState)
    }

    override suspend fun main() {
        ActivityUtils.finishAllActivitiesExceptNewest()

        if (mLastTab == null) mLastTab = mBinding.homeTab
        else mLastTab?.let { tabClick(it) }
        onNavigationItemSelectedImpl(0)

        mBinding.cartTab.clickIsLogin {
            tabClick(it)
        }

        mBinding.personalTab.clickIsLogin {
            tabClick(it)
        }

        while (isActive) {
            events.receive()
        }
    }

    private var mLastTab: View? = null

    fun tabClick(view: View) {
        if (mLastTab?.id == view.id) return
        mLastTab = view
        resetMenuState()
        when (view.id) {
            R.id.homeTab -> {
                onNavigationItemSelectedImpl(0)
                mBinding.homeTv.setTextColor(ContextCompat.getColor(this, R.color.colorPrimary))
                mBinding.homeIcon.setImageResource(R.mipmap.ic_tab_one_select)
            }
            R.id.typeTab-> {
                onNavigationItemSelectedImpl(1)
                mBinding.typeTv.setTextColor(ContextCompat.getColor(this, R.color.colorPrimary))
                mBinding.typeIcon.setImageResource(R.mipmap.ic_tab_two_select)
            }
            R.id.cartTab -> {
                onNavigationItemSelectedImpl(2)
                mBinding.cartTv.setTextColor(ContextCompat.getColor(this, R.color.colorPrimary))
                mBinding.cartIcon.setImageResource(R.mipmap.ic_tab_three_select)
            }
            R.id.personalTab -> {
                onNavigationItemSelectedImpl(3)
                mBinding.personalTv.setTextColor(ContextCompat.getColor(this, R.color.colorPrimary))
                mBinding.personalIcon.setImageResource(R.mipmap.ic_tab_four_select)
            }
        }
    }

    private fun resetMenuState() {
        mBinding.homeTv.setTextColor(ContextCompat.getColor(this, R.color.color_D1D1D1))
        mBinding.homeIcon.setImageResource(R.mipmap.ic_tab_one_not)
        mBinding.typeTv.setTextColor(ContextCompat.getColor(this, R.color.color_D1D1D1))
        mBinding.typeIcon.setImageResource( R.mipmap.ic_tab_two_not)
        mBinding.cartTv.setTextColor(ContextCompat.getColor(this, R.color.color_D1D1D1))
        mBinding.cartIcon.setImageResource(R.mipmap.ic_tab_three_not)
        mBinding.personalTv.setTextColor(ContextCompat.getColor(this, R.color.color_D1D1D1))
        mBinding.personalIcon.setImageResource(R.mipmap.ic_tab_four_not)
    }

    override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (!isBack) {
                isBack = true
                onCenterToast(getString(R.string.press_exit_program))
                return true
            }
        }
        return super.onKeyUp(keyCode, event)
    }

    fun onNavigationItemSelectedImpl(menuItemId: Int) {
        if (menuItemId == lastId) return

        val fm: FragmentManager = supportFragmentManager
        val transaction: FragmentTransaction = fm.beginTransaction()
        val lastKey = keyOf(lastId)

        //隐藏上一个页面
        val lastFragment: Fragment? = fm.findFragmentByTag(lastKey)
        if (lastFragment != null) transaction.hide(lastFragment)

        //显示点击的菜单
        val key = keyOf(menuItemId)
        var fragment: Fragment? = fm.findFragmentByTag(key)
        if (fragment != null) transaction.show(fragment)
        else {
            fragment = getFragmentForMenuItem(menuItemId)
            transaction.add(R.id.fragment_container, fragment, key)
        }
        transaction.commit()
        lastId = menuItemId
    }

    private fun getFragmentForMenuItem(id: Int): Fragment {
        var fragment = fragments[id]
        if (fragment != null) {
            return fragment
        }
        when (id) {
            0 -> fragment = HomeFragment()
            1 -> fragment = CategoryFragment()
            2 -> fragment = CartFragment()
            3 -> fragment = MineFragment()
            else -> throw IllegalStateException("Not found fragment for item #$id")
        }
        fragments.put(id, fragment)
        return fragment
    }

    private fun keyOf(@IdRes id: Int): String {
        return "fragment:$id"
    }

    override fun onDestroy() {
        Global.destroy()
        super.onDestroy()
    }

    override fun onStart() {
        super.onStart()
        var position = SPUtils.getInstance().getInt("home",-1)
        if(position >= 0) goHome(position)
        SPUtils.getInstance().remove("home")
    }

    fun goHome(position:Int? = 0,typeID:String? = null){
        when (position) {
            0 -> tabClick(mBinding.homeTab)
            2 -> tabClick(mBinding.cartTab)
            1 -> {
                tabClick(mBinding.typeTab)
                var fragment = getFragmentForMenuItem(position)
                if(fragment is CategoryFragment) {
                    fragment.onTypeSelect(typeID)
                }
            }
        }
    }



}